﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using HousingInfo.Library;

namespace WebHousingInfo
{
    public partial class DangTinDoanhNghiep : System.Web.UI.Page
    {
        private static string mode = null, modeback = null;
        private static NewsBussinessBO newsbussinessbo;
        private static bool retun, checkex = true;
        private static string _fileImageName;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["UserName"] == null)
                    Response.Redirect("DangNhap.aspx");
                mode = Request.QueryString["iddn"];
                modeback = Request.QueryString["back"];
                if (mode != null)
                {
                    btnxoa.Visible = true;
                    newsbussinessbo = NewsBussinessBO.GetNewsBussinessBO(int.Parse(mode));
                    if (newsbussinessbo.IsActive == true)
                        btnketthuc.Visible = true;
                    lblngaydang.Text = "<br /> (Ngày đăng: " + Convert.ToDateTime(newsbussinessbo.CreatedDate).ToShortDateString() + ", " + "ngày hết hạn: " + Convert.ToDateTime(newsbussinessbo.ExpireDate).ToShortDateString() + ", " + "ngày chỉnh sửa gần nhất " + Convert.ToDateTime(newsbussinessbo.UpdatedDate).ToShortDateString() + ")";
                    lblngaydang.Visible = true;
                    OptionBO optionbo;
                    optionbo = OptionBO.GetNameOptionBO("SoLanGiaHanTinDoanhNghiep");
                    if (newsbussinessbo.ExpireDate <= DateTime.Now)
                    {
                        pn_result.Visible = true;
                        btndangtin.Visible = false;
                        if (Convert.ToInt32(optionbo.OptionValue) <= newsbussinessbo.NumExtension)
                        {
                            lblthongbao.Text = "Thông Báo: Tin này đã hết hạn và hết quyền gia hạn. Để tiếp tục đăng tin bạn vui lòng ";
                            lbtgiahan.Text = "Đăng tin mới";
                            checkex = false;
                        }
                    }
                    txtname.Text = newsbussinessbo.BussinessName;
                    if (newsbussinessbo.UrlImage != "" && newsbussinessbo.UrlImage != null)
                    {
                        FileUpload_ImageBussiness.Visible = false;
                        txtimage.Text = newsbussinessbo.UrlImage;
                        txtimage.Visible = true;
                        lbtchangeimage.Visible = true;
                    }
                    txtaddress.Text = newsbussinessbo.BussinessAddress;
                    txtwebsite.Text = newsbussinessbo.BussinessWebsite;
                    txtphone.Text = newsbussinessbo.BussinessPhone;
                    txtemail.Text = newsbussinessbo.Email;
                    dltimepost.SelectedValue = (Convert.ToDateTime(newsbussinessbo.ExpireDate) - Convert.ToDateTime(newsbussinessbo.CreatedDate)).Days.ToString();
                    //newsHouseBO.ExpireDate = DateTime.Now.AddDays(double.Parse(dltimepost.SelectedValue));
                    txtcontent.Text = newsbussinessbo.BussinessContent;
                    dltimepost.Enabled = false;
                    btndangtin.Text = "Cập nhật";
                    btndangtin.Focus();
                }
                else
                    btndangtin.Focus();
            }

        }

        public bool checkurlimage(string imagestring)
        {
            var pathFileImage = Server.MapPath("TotalUpload/ImagesTotal/" + imagestring);
            if (File.Exists(pathFileImage))
            {
                return true;
            }
            else return false;
        }

        public NewsBussinessBO GetBussinessBO()
        {
            try
            {
                if (mode != null)
                {
                    newsbussinessbo = NewsBussinessBO.GetNewsBussinessBO(int.Parse(mode));
                    return newsbussinessbo;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }

        protected void btndangtin_Click(object sender, EventArgs e)
        {
            if (Session["UserName"] == null)
                Response.Redirect("DangNhap.aspx");
            retun = true;
            if (mode != null)
            {
                //mode sua tin
                newsbussinessbo = NewsBussinessBO.GetNewsBussinessBO(Convert.ToInt32(mode));
                newsbussinessbo.BussinessName = txtname.Text;
                newsbussinessbo.BussinessPhone = txtphone.Text;
                newsbussinessbo.BussinessAddress = txtaddress.Text;
                newsbussinessbo.BussinessWebsite = txtwebsite.Text;
                newsbussinessbo.BussinessContent = txtcontent.Text;
                newsbussinessbo.Email = txtemail.Text;
                newsbussinessbo.IsActive = false;
                newsbussinessbo.UpdatedDate = DateTime.Now;
                if (FileUpload_ImageBussiness.Visible == true)
                {
                    deleteExitsImage(newsbussinessbo.UrlImage);
                    newsbussinessbo.UrlImage = "";
                    if (FileUpload_ImageBussiness.FileName.Length > 0)
                    {
                        postImage(FileUpload_ImageBussiness);
                        if (retun == false) return;
                    }
                }
                //thuc hien code neu co thong tin gia han 
                if (pn_giahan.Visible == true)
                {
                    newsbussinessbo.IsExtension = true;
                    newsbussinessbo.NumExtension += 1;
                    newsbussinessbo.ExpireDate = DateTime.Now.AddDays(double.Parse(dltimeex.SelectedValue));
                    newsbussinessbo.PostDate = DateTime.Now;
                    newsbussinessbo.ExtensionDate = DateTime.Now;                    
                }
                try
                {
                    newsbussinessbo.Save();
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                    "alert('Cập nhật thành công.')", true);
                    if (modeback != null && modeback != "")
                        Response.Redirect("QuanlytinDoanhNghiep.aspx?xemtindoanhnghiep=" + modeback);
                    else Response.Redirect("QuanlytinDoanhNghiep.aspx");
                }
                catch
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                    "alert('Cập nhật thất bại.')", true);
                }
            }
            else
            {
                //mode dang tin moi
                if (NewsBussinessBOList.CheckNewsBusinessName(txtname.Text.Trim()) == false)
                {
                    newsbussinessbo = NewsBussinessBO.NewNewsBussinessBO();
                    newsbussinessbo.UserName = Session["UserName"].ToString();

                    newsbussinessbo.BussinessName = txtname.Text;
                    if (FileUpload_ImageBussiness.FileName.Length > 0)
                    {
                        postImage(FileUpload_ImageBussiness);
                        if (retun == false) return;
                    }
                    else newsbussinessbo.UrlImage = "";
                    newsbussinessbo.BussinessAddress = txtaddress.Text;
                    newsbussinessbo.BussinessWebsite = txtwebsite.Text;
                    newsbussinessbo.BussinessPhone = txtphone.Text;
                    newsbussinessbo.BussinessContent = txtcontent.Text;
                    newsbussinessbo.Email = txtemail.Text;
                    if (OptionBO.GetNameOptionBO("tudongduyettinDoanhnghiep").OptionValue == "True")
                        newsbussinessbo.IsActive = true;
                    else
                        newsbussinessbo.IsActive = false;
                    newsbussinessbo.IsExtension = false;
                    newsbussinessbo.CreatedDate = DateTime.Now;
                    newsbussinessbo.UpdatedDate = DateTime.Now;
                    newsbussinessbo.NumExtension = 0;
                    newsbussinessbo.PostDate = DateTime.Now;
                    newsbussinessbo.ExpireDate = DateTime.Now.AddDays(double.Parse(dltimepost.SelectedValue));
                    try
                    {
                        newsbussinessbo.Save();
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                    "alert('Đăng tin thành công.')", true);
                        if (modeback != null && modeback != "")
                            Response.Redirect("QuanlytinDoanhNghiep.aspx?xemtindoanhnghiep=" + modeback);
                        else Response.Redirect("QuanlytinDoanhNghiep.aspx");
                    }
                    catch
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                    "alert('Đăng tin thất bại. Xin hay thử lại.')", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                    "alert('Doanh nghiệp này đã tồn tại.')", true);
                }

            }
        }

        private void postImage(FileUpload filename)
        {
            try
            {
                if (filename.HasFile)
                {
                    if (filename.FileBytes.Length < 512000)
                    {
                        _fileImageName = filename.FileName.Replace(" ", "_");

                        string formatFile = Path.GetExtension(_fileImageName);
                        formatFile = formatFile.ToLower();
                        //kiem tra dinh dang cho phep upload
                        if (formatFile.Equals(".jpg") || formatFile.Equals(".gif") || formatFile.Equals(".png") || formatFile.Equals(".JPG") || formatFile.Equals(".GIF") || formatFile.Equals(".PNG"))
                        {
                            //kiem tra file da ton tai
                            string filePath = HttpContext.Current.Server.MapPath("TotalUpload/ImagesTotal/" + _fileImageName);
                            if (File.Exists(filePath))
                            {
                                //neu ton tai thi doi ten
                                _fileImageName = ImageFileName(_fileImageName);
                            }
                            //thuc hien luu file
                            try
                            {
                                filename.SaveAs(Server.MapPath("TotalUpload/ImagesTotal/" + _fileImageName));
                                try
                                {
                                    newsbussinessbo.UrlImage = _fileImageName;
                                }
                                catch
                                {
                                    newsbussinessbo.UrlImage = "";
                                }
                            }
                            catch (Exception)
                            {
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Có một số vấn đề xả ra trong khi lưu. Xin hay thử lại.')", true);
                                retun = false;
                                return;
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chỉ được upload các định dạng ảnh (.jpg , .gif, .png)')", true);
                            retun = false;
                            return;
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Kích thước ảnh không quá 500Kb.')", true);
                        retun = false;
                        return;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chưa chọn hỉnh ảnh đại diện. !')", true);
                    retun = false;
                    return;
                }
            }
            catch { }
        }

        private static string ImageFileName(string fileName)
        {
            Random r = new Random();
            return r.Next(0, 10000).ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + fileName;
        }

        private void deleteExitsImage(string filedelete)
        {
            try
            {
                var pathFileImage = Server.MapPath("TotalUpload/ImagesTotal/" + filedelete);
                FileInfo fileInfo;
                if (File.Exists(pathFileImage))
                {
                    fileInfo = new FileInfo(pathFileImage);
                    fileInfo.Delete();
                }
            }
            catch
            {
            }
        }

        protected void btnhuy_Click(object sender, EventArgs e)
        {
            if (modeback != null && modeback != "")
                Response.Redirect("QuanlytinDoanhNghiep.aspx?xemtindoanhnghiep=" + modeback);
            else Response.Redirect("QuanlytinDoanhNghiep.aspx");
        }

        protected void lbtchangeimage_Click(object sender, EventArgs e)
        {
            txtimage.Visible = false;
            FileUpload_ImageBussiness.Visible = true;
            lbtchangeimage.Visible = false;
        }

        protected void lbtgiahan_Click(object sender, EventArgs e)
        {
            if (checkex == true)
            {
                pn_giahan.Visible = true;
                btndangtin.Visible = true;
                btndangtin.Focus();
            }
            else
            {
                Response.Redirect("DangTinDoanhNghiep.aspx");
            }
        }

        protected void btnxoa_Click(object sender, EventArgs e)
        {
            try
            {
                NewsBussinessBO.DeleteNewsBussinessBO(Convert.ToInt32(mode));
                
            }
            catch { }
        }

        protected void btnketthuc_Click(object sender, EventArgs e)
        {
            try
            {
                newsbussinessbo = NewsBussinessBO.GetNewsBussinessBO(int.Parse(mode));
                newsbussinessbo.IsActive = false;
                newsbussinessbo.Save();
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Đã kết thúc đăng tin Doanh Nghiệp này.')", true);
            }
            catch
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Kết thúc đăng tin thất bại.')", true);
            }
        }
    }
}
